<?php

declare(strict_types=1);

namespace app\api\controller\v1;

use app\api\helpers\v1\traits\FileUpload;
use app\api\model\v1\AdminLog;
use app\api\model\v1\AuthGroupAccess;
use app\api\model\v1\AuthWxGroupAccess;
use app\api\model\v1\Unit;
use app\api\model\v1\Users;
use app\api\validate\v1\LoginValidate;
use app\api\validate\v1\UserValidate;
use app\BaseController;
use think\exception\ValidateException;
use think\facade\Config;
use think\facade\Env;
use think\Request;

class Wechat extends BaseController
{
    use FileUpload;

    /**
     * @User: 刘海龙
     * @Date: 2021/9/26
     * @Time: 10:18
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 微信前端用户
     */
    public function wechatList()
    {
        //获取每页显示的条数
        $limit = $this->request->param('limit', 10);
        $map = [];
        if (!$this->is_super) {
            $childrenList = $this->search->getChildrenIds($this->request->unit_id, true);
            $map[] = array('unit_id', 'in', $childrenList);
        } else {
            $map = [];
        }
        if ($this->request->has('username') && !empty($this->request->param('username'))) {
            $map[] = ['username', 'like', '%' . $this->request->param('username') . '%'];
        }
        $where = [];
        if ($this->request->has('unit_s_id') && !empty($this->request->param('unit_s_id'))) {
            $unit_parent_arr = $this->request->param('unit_s_id');
            $children =  $this->search->getChildrenIds(intval(end($unit_parent_arr)), true);
            $where[] = ['unit_id', 'in', $children];
        }
        $where[] = ['wx_role_id', 'in', ['2','4']];
        $data = Users::with(['unit', 'industry'])->where($map)->where($where)->paginate($limit)->each(function ($item, $key) {
            $unit_parent =  $this->search->getParents($item['unit_id']);

            $item['unit_parent'] = $unit_parent ?? [];
            return $item;
        });;

        return $this->response($data);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/26
     * @Time: 10:16
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 新增微信前端用户
     */
    public function wechatSave()
    {
        $id = $this->request->param('id', 0);

        try {

            $validator = $this->validate(
                $this->request->param(),
                UserValidate::rules($id),
                UserValidate::msg()
            );
            if ($validator) {
                $data = $this->request->except(['password_confirm','unit_parent','unit','industry']);
                if (empty($data['unit_id'])) {
                    $data['unit_id'] = 0;
                }
                if (intval($id) === 0) {
                    $data['password'] = password_hash(!empty($data['password']) ? $data['password'] : '111111', PASSWORD_DEFAULT);
                    $data['create_id'] = $this->request->uid ?? 0;
                    $user = Users::create($data);
                } else {
                    if (empty($data['password'])) {
                        unset($data['password']);
                    } else {
                        $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
                    }
                    $user = Users::find($id);
                    $user->update($data);
                    //添加用户角色中间表信息

                }
                //                $access = AuthWxGroupAccess::where(['wx_uid' => $user->id])->find();
                //                if (is_null($access)) {
                //                    //添加用户角色中间表信息
                //                    AuthWxGroupAccess::create(['wx_uid' => $user->id, 'wx_group_id' => $data['group_wx_id']]);
                //                } else {
                //                    AuthWxGroupAccess::where(['wx_uid' => $user->id])->update(['wx_group_id' => $data['group_wx_id']]);
                //                }


                AdminLog::record(intval($id) === 0 ? '新增前端用户' : '编辑前端用户', $data, $this->request->uid, $this->request->username);

                return $this->response();
            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->response(403, $e->getError());
        }
    }


    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/9/26
     * @Time: 10:27
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除用户
     */
    public function wechatDelete($id)
    {
        $ids = explode(',', $id);
        foreach ($ids as $id) {
            $user = Users::find($id);
            if (is_null($user)) {
                return $this->response(404, '此用户不存在');
            }
            //->force()
            $user->delete();
            AdminLog::record('删除前端用户', $this->request->param(), $this->request->uid, $this->request->username);
        }
        return $this->response();
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/9/30
     * @Time: 14:51
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 微信登录
     */
    public function wxLogin()
    {
        $data = $this->request->param();
        try {
            $this->validate(['mobile' => $data['mobile'], 'password' => $data['password']], LoginValidate::class);
            if (!$user = Users::with(['unit'])->where('mobile', $data['mobile'])->find()) {
                return $this->response(403, '用户名不存在');
            }
            if (!password_verify($data['password'], $user->password)) {
                return $this->response(403, '密码错误');
            }
            $token = $this->token->createToken($user->id);
            $user->token = $token;
            $user->login_time = time();
            $user->save();
        } catch (ValidateException $exception) {
            // 验证失败 输出错误信息
            return $this->response(403, $exception->getError());
        }
        if ($user['unit'] === null) {
            $user['unit'] = [
                'unit_title' => '管理员'
            ];
        }
        return $this->response($user);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/30
     * @Time: 14:33
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 重新获取token
     */
    public function getToken()
    {
        $uid = $this->request->param('uid');
        $user = Users::find($uid);
        if (is_null($user)) {
            return $this->response(500, '用户不存在');
        }
        $token = $this->token->createToken($uid);
        $user->token = $token;
        $user->login_time = time();
        $user->save();
        return $this->response($user);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/30
     * @Time: 14:34
     * @return \think\response\Json
     * 验证token
     */
    public function tokenVerify()
    {
        $token = $this->request->param('token');
        if (!$token) {
            return $this->response(500, 'token不允许为空');
        }
        $valid = $this->verifyToken($token);
        $arr = ['isValid' => $valid];
        return json($arr);
    }

    /**
     * @param $token
     * @User: 刘海龙
     * @Date: 2021/9/30
     * @Time: 14:34
     * @return bool
     * 验证token
     */
    public function verifyToken($token)
    {
        $exist = $this->token->checkTokenJWT($token);
        if ($exist['code'] === 10000) {
            return true;
        } else {
            return false;
        }
    }
}
